package com.chow.test;

import java.io.Serializable;
//import java.net.HttpCookie;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CookieManager implements Serializable {
	public static final long serialVersionUID = -2653038934719086755L;
	public static final String SET_COOKIE = "Set-Cookie";
	public static final String COOKIE_VALUE_DELIMITER = ";";
	public static final String COOKIE = "Cookie";
	public static final String DOT = ".";
	public Map<String, Map<String, HttpCookie>> store;

	public CookieManager() {
		this.store = new HashMap<String, Map<String, HttpCookie>>();
	}

	public void setCookies(URLConnection conn) {
		String host = conn.getURL().getHost();
		String path = conn.getURL().getPath();
		path = this.getPath(path);

		StringBuilder sb = new StringBuilder();
		Iterator<String> keys = this.store.keySet().iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			if (!(key.equals(DOT + host) || host.endsWith(key)))
				continue;
			Map<String, HttpCookie> cookies = this.store.get(key);
			Iterator<String> names = cookies.keySet().iterator();
			while (names.hasNext()) {
				String name = names.next();
				HttpCookie cookie = cookies.get(name);
				if (!cookie.getPath().equalsIgnoreCase(path))
					continue;
				sb.append(cookie.toString());
				System.out.println("> " + cookie.toString());
				sb.append(COOKIE_VALUE_DELIMITER);
			}
		}

		if (sb.length() > 0) {
			String str = sb.toString();
			if (str.endsWith(COOKIE_VALUE_DELIMITER))
				str = str.substring(0,
						str.length() - COOKIE_VALUE_DELIMITER.length());
			conn.setRequestProperty(COOKIE, str);
		}
	}

	public void storeCookies(URLConnection conn) {
		String host = conn.getURL().getHost();
		String path = conn.getURL().getPath();
		path = this.getPath(path);

		String value = null;
		for (int i = 0; (value = conn.getHeaderField(i)) != null; i++) {
			String name = conn.getHeaderFieldKey(i);
			if (!SET_COOKIE.equalsIgnoreCase(name))
				continue;
			List<HttpCookie> cookies = HttpCookie.parse(value);
			for (HttpCookie cookie : cookies) {
				String key = host;
				if (cookie.getDomain() != null
						&& !cookie.getDomain().startsWith(DOT))
					cookie.setDomain(DOT + cookie.getDomain());

				if (cookie.getDomain() != null)
					key = cookie.getDomain();

				if (cookie.getPath() == null)
					cookie.setPath(path);

				Map<String, HttpCookie> domainCookies = this.store.get(key);
				if (domainCookies == null) {
					domainCookies = new HashMap<String, HttpCookie>();
					this.store.put(key, domainCookies);
				}

				HttpCookie oldCookie = domainCookies.get(cookie.getName());
				if (oldCookie != null)
					domainCookies.remove(oldCookie);

				if (cookie.getMaxAge() != 0) {
					domainCookies.put(cookie.getName(), cookie);
					System.out.println("< " + cookie.toString());
				}

			}
		}
	}

	private String getPath(String path) {
		if (path == null || path == ""
				|| path.lastIndexOf("/") == path.indexOf("/"))
			return "/";

		return path.substring(0, path.lastIndexOf("/"));
	}

	public String toString() {
		return this.store.toString();
	}
}
